package cn.xlbweb.sso.service.impl;

import cn.xlbweb.sso.entity.ClientDTO;
import cn.xlbweb.sso.entity.ProjectDTO;
import cn.xlbweb.sso.entity.ServerDTO;
import cn.xlbweb.sso.entity.UserDTO;
import cn.xlbweb.sso.entity.vo.OnlineUserVO;
import cn.xlbweb.sso.repository.ClientRepository;
import cn.xlbweb.sso.repository.ProjectRepository;
import cn.xlbweb.sso.repository.ServerRepository;
import cn.xlbweb.sso.repository.UserRepository;
import cn.xlbweb.sso.server.LayuiTable;
import cn.xlbweb.sso.service.IOnlineUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: bobi
 * @date: 2019-04-04 21:46
 * @description:
 */
@Service
public class OnlineUserServiceImpl implements IOnlineUserService {

    @Autowired
    private ClientRepository clientRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private ProjectRepository projectRepository;

    @Autowired
    private ServerRepository serverRepository;

    @Override
    public LayuiTable list(Integer page, Integer limit) {
        // 分页
        Pageable pageable = PageRequest.of(page - 1, limit);
        Page<ClientDTO> clientPage = clientRepository.findAll(pageable);
        List<ClientDTO> clientList = clientPage.getContent();
        Long count = clientPage.getTotalElements();
        // 组装VO对象
        List<OnlineUserVO> onlineUserList = new ArrayList<>();
        for (ClientDTO client : clientList) {
            OnlineUserVO onlineUser = new OnlineUserVO();
            onlineUser.setId(client.getId());
            onlineUser.setToken(client.getToken());
            onlineUser.setJsessionId(client.getJsessionId());
            onlineUser.setClientUrl(client.getClientUrl());
            // 用户名
            UserDTO user = userRepository.findById(client.getUserId()).get();
            onlineUser.setUsername(user.getUsername());
            // 系统名称
            ProjectDTO project = projectRepository.findById(client.getProjectId()).get();
            onlineUser.setProjectName(project.getName());
            // 浏览器
            ServerDTO server = serverRepository.findByToken(client.getToken());
            onlineUser.setBrowserName(server.getBrowser());
            // 操作系统
            onlineUser.setOsName(server.getOs());
            onlineUserList.add(onlineUser);
        }
        return LayuiTable.success(count, onlineUserList);
    }
}
